<?php
if (!empty($_POST)) {
    if (isset($_POST['register'])) {
        $errors = array();
        $email = $_POST["email"];
        $username = $_POST["username"];
        $password = $_POST["password"];
        $confirm_pass = $_POST["passwordc"];
        if (minMaxRange(5, 25, $username)) {
            $errors[] = "Username must be no fewer than 5 characters or greater than 25.";
        }
        if (minMaxRange(8, 50, $password) && minMaxRange(8, 50, $confirm_pass)) {
            $errors[] = "Password must be no fewer than 8 characters or greater than 50.";
        } else if ($password != $confirm_pass) {
            $errors[] = "Passwords must match.";
        }
        if (!isValidEmail($email)) {
            $errors[] = "Invalid email specified.";
        }
        if (count($errors) == 0) {
            $user = new User($username, $password, $email);
            if (!$user->status) {
                if ($user->username_taken)
                    $errors[] = "Username " . $username . " is already in use.";
                if ($user->email_taken)
                    $errors[] = "Email " . $email . " is already in use.";
            }
            else {
                if (!$user->userCakeAddUser()) {
                    if ($user->mail_failure)
                        $errors[] = "Fatal error attempting mail, contact your server administrator";
                    if ($user->sql_failure)
                        $errors[] = "Fatal SQL error attempting to insert user.";
                }
            }
        }
    }
}
?>

<?php
if (!empty($_POST)) {
    if (isset($_POST['login'])) {
        $errors = array();
        $username = trim($_POST["username"]);
        $password = trim($_POST["password"]);

        //Perform some validation
        //Feel free to edit / change as required
        if ($username == "") {
            $errors[] = "Username is required.";
        }
        if ($password == "") {
            $errors[] = "Password is required";
        }

        //End data validation
        if (count($errors) == 0) {
            //A security note here, never tell the user which credential was incorrect
            if (!usernameExists($username)) {
                $errors[] = "Username or password is invalid";
            } else {
                $userdetails = fetchUserDetails($username);

                //See if the user's account is activation
                if ($userdetails["active"] == 0) {
                    $errors[] = "Your account is not active. Check your emails / spam folder to find your account activation instructions.";
                } else {
                    //Hash the password and use the salt from the database to compare the password.
                    $entered_pass = generateHash($password, $userdetails["password"]);

                    if ($entered_pass != $userdetails["password"]) {
                        //Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
                        $errors[] = "Username or password is invalid";
                    } else {
                        //Passwords match! we're good to go'
                        //Construct a new logged in user object
                        //Transfer some db data to the session
                        $loggedInUser = new loggedInUser();
                        $loggedInUser->email = $userdetails["email"];
                        $loggedInUser->user_id = $userdetails["user_id"];
                        $loggedInUser->hash_pw = $userdetails["password"];
                        $loggedInUser->display_username = $userdetails["username"];
                        $loggedInUser->clean_username = $userdetails["username_clean"];

                        //Update last sign in
                        $loggedInUser->updateLastSignIn();
                        $_SESSION["userCakeUser"] = $loggedInUser;

                        //Redirect to user account page
//                        header("Location: ./");
                        ?>
                        <script type="text/javascript">
                            jQuery(document).ready(function(){
                                location.reload();
                            });
                        </script>
                        <?php
                        die;
                    }
                }
            }
        }
    }
}
?>


<?php
if (!empty($_POST)) {
    if (count($errors) > 0) {
        $list = "";
        foreach ($errors as $issue)
            $list.="<p class='label label-important'>" . $issue . "</p>";
        ?> 
        <?php echo $list; ?>
        <?php
    } else {
        $message = "You have successfully registered. You can now login.";
        //Is email activation enabled?
        if ($emailActivation)
            $message = "You have successfully registered. You will soon receive an activation email. You must activate your account before logging in.";
        ?> 
        <div>
            <p class="label label-success"><?php echo $message ?></p>
        </div>
        <?php
    }
}
?>

<?php if (!isUserLoggedIn()) { ?>
    <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post" class="well">
        <input type="hidden" name="login" value="1" />
        <input type="text" name="username" style="width: 90%;" placeholder="Username ..." />
        <br />
        <input type="password" name="password" style="width: 90%;" placeholder="Password ..." />
        <br />
        <button type="submit" class="btn">Login</button>

        <br /><br />
        <span class="label" style="width: 90%;">
            <span>Don't have account?</span>
            <a href="javascript:showRegisterDialog();">Register here</a>
        </span>
    </form>
    <div class="modal hide fade in" id="register_dialog">
        <form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
            <input type="hidden" name="register" value="1" />
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h3>Registration form</h3>
            </div>
            <div class="modal-body">

                <input type="text" name="username" placeholder="Username ..." />
                <br />
                <input type="password" name="password" placeholder="Password ..." />
                <br />
                <input type="password" name="passwordc" placeholder="Re-type password ..." />
                <br />
                <input type="text" name="email" placeholder="Email ..." />
                <br />

            </div>
            <div class="modal-footer">
                <a href="#" class="btn" data-dismiss="modal">Close</a>
                <input type="submit"  class="btn btn-primary" value="Register" />
            </div>
        </form>
    </div>
<?php } ?>
<div class="span3 page-header">
    <h2>Welcome</h2>
    <small>Message</small>
</div>
<script type="text/javascript">
    $(document).ready(function(){
        
    });
    function showRegisterDialog(){
        $('#register_dialog').modal('show'); 
    }
</script>
